from rest_framework import serializers

from goods.models import SKU


class AddCartsSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品ID', min_value=1)
    count = serializers.IntegerField(label='数量', min_value=1)
    selected = serializers.BooleanField(label='是否勾选', default=True)

    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs.get('sku_id'))
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return attrs


class GetCartsSerialier(serializers.ModelSerializer):
    count = serializers.IntegerField(label='数量', min_value=1)
    selected = serializers.BooleanField(label='是否勾选', default=True)

    class Meta:
        model = SKU
        fields = ['id', 'name', 'default_image_url', 'price', 'count', 'selected']


class DeteleCartsSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品ID', min_value=1)

    def validate(self, attrs):
        sku_id = attrs.get('sku_id')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        return attrs


class CheckAllSerializer(serializers.Serializer):
    selected = serializers.BooleanField(label='是否全选')
